﻿using BLL;
using Model;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.其他窗体;
using 后整理管理系统.数据分析;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.设置窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 打卷报表 : Form
    {
        private List<JuanHaoTable> juanlist = new List<JuanHaoTable>();
        public 打卷报表()
        {
            InitializeComponent();
            CreateGrid.Create(this.Name , gridView2);
            CreateGrid.Create(this.Name, Gridview1);
            CreateGrid.Create(this.Name, uiDataGridView2,"gridView2");
            CreateGrid.Create(this.Name, DGVDelete, "gridView2");
            gridView2.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            uiDataGridView2.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            gridView2.OptionsCustomization.AllowSort = true;
            dateEdit2.DateTime = DateTime.Now;
            dateEdit1.DateTime = DateTime.Now.Date ;
            cmbmaitou.Items.AddRange ( Tools.获取模板.获取所有模板(PrintPath.唛头模板).ToArray ());
            cmbmaitou.SelectedIndex = 0;
            Gridview1.OptionsCustomization.AllowSort = true;
            Query();
        }     

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Query();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new JuanHaoTable () };
            fm.ShowDialog();
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView2);
        }
        private void Query()
        {
            this.ShowWaitForm("正在查询，请等待.............");  
            juanlist =JuanHaoTableService.GetJuanHaoTablelst(x => x.rq >= dateEdit1.DateTime.Date  && x.rq <= dateEdit2.DateTime.Date .AddDays (1)  && x.SampleName .Contains(txtpingming.Text) && x.guige.Contains(txtguige.Text) && x.GangHao.Contains(txtganghao.Text) && x.kuanhao.Contains(txthuohao.Text) 
            && x.yanse.Contains(txtsehao.Text) && x.CustomerName.Contains(txtkehu.Text) && x.SampleNum.Contains(txtBianhao.Text) && x.OrderNum .Contains(txtOrderNum.Text)&&x.MachineID.Contains (txtmachine.Text)&&x.CheckID .Contains (cmbcheckname.Text ) );
            gridControl2.DataSource = juanlist;
            try
            {
                var stocks = Connect.CreatConnect().Query($"select sum(JuanHaoTable.biaoqianmishu ) as biaoqianmishu,sum(JuanHaoTable.mishu) as yijianmishu,COUNT(*) " +
                    $"as yijianjuanshu,(sum(juanhaotable.mishu)-StockTable.ms ) as difference,juanhaotable.ReceiptNo as rkdh," +
                    $"GangHao as gh,customerName as customName,SampleName as pm,yanse as ys,juanhaotable.danwei as danwei ,guige as gg,JuanHaoTable.Houzhengli,lxr.fullname as Fullname," +
                    $"StockTable.ms as ms ,stocktable.js as js,(select sum( toupimishu) from danjumingxitable where danjumingxitable.danhao like 'SC%' and rkdh=juanhaotable.ReceiptNo and ganghao=juanhaotable.ganghao and houzhengli=juanhaotable.houzhengli) as yifaNum  from JuanHaoTable left join stocktable on stocktable.id=juanhaotable.StockID  left join lxr on juanhaotable.customername=lxr.mc where" +
                    $" JuanHaoTable.rq between '{dateEdit1.DateTime.Date }' and '{dateEdit2.DateTime.Date.AddDays(1)}' and " +
                    $"JuanHaoTable.samplename like '%{txtpingming.Text }%' and " +
                    $"JuanHaoTable.sampleNum like '%{txtBianhao.Text }%' and " +
                    $"JuanHaoTable.yanse like '%{txtsehao.Text }%' and " +
                    $"JuanHaoTable.CustomerName like '%{txtkehu.Text }%' and " +
                    $"JuanHaoTable.OrderNum like '%{txtOrderNum.Text }%' and " +
                    $"JuanHaoTable.guige like '%{txtguige.Text }%' and " +
                    $"JuanHaoTable.GangHao like '%{txtganghao.Text }%' and " +
                    $"JuanHaoTable.kuanhao like '%{txthuohao.Text }%' and " +
                    $"JuanHaoTable.CheckID like '%{cmbcheckname.Text }%' and " +
                    $"JuanHaoTable.MachineID like '%{txtmachine .Text }%' " +
                    $" group by stocktable.rkdh, stocktable.js, JuanHaoTable.GangHao,juanhaotable.ReceiptNo" +
                    $" ,JuanHaoTable.CustomerName,JuanHaoTable.SampleName,JuanHaoTable.yanse" +
                    $",JuanHaoTable.guige,JuanHaoTable.Houzhengli,StockTable.ms ,lxr.Fullname,juanhaotable.danwei,JuanHaoTable.CheckID,JuanHaoTable.MachineID");
                gridControl1.DataSource = stocks;
                var deletejuans = new List<JuanHaoTable>();
                foreach (var del in DeleteLogService.GetDeleteLoglst(x => x.date >= dateEdit1.DateTime && x.date <= dateEdit2.DateTime && x.Log.Contains("JuanHao")))
                {
                    deletejuans.Add(JsonJavaScriptSerializer.FromJSON<JuanHaoTable>(del.Log));
                }
                gridControl4.DataSource = deletejuans;
                this.HideWaitForm();
            }
            catch (Exception ex)
            {
                this.HideWaitForm();
                Tools.ShowMessageBox.ShowErrorBox(ex.Message);
            }
            //uiProgressIndicator1.Dispose();
        }
        private void 删除卷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string del = "您确定要删除\r\n";
            foreach (var i in gridView2.GetSelectedRows())
            {
                //Sunny.UI.UIMessageDialog.ShowSuccessDialog (this, 可发卷BLL.卷删除(gridView2.GetRowCellValue(i, "JuanHao").ToString ()));
                del += "卷号是" + gridView2.GetRowCellValue(i, "JuanHao").ToString() + "  品名是:" + gridView2.GetRowCellValue(i, "SampleName").ToString() + "  颜色是:" + gridView2.GetRowCellValue(i, "yanse").ToString() + "  缸号是:" + gridView2.GetRowCellValue(i, "SampleName").ToString();
                del += "  款号是:" + gridView2.GetRowCellValue(i, "kuanhao").ToString() + "\r\n";
            }
            del += "这些卷吗？";
            var res = MessageBox.Show(del, this.Name, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                foreach (var i in gridView2.GetSelectedRows())
                {
                    可发卷BLL.卷删除(gridView2.GetRowCellValue(i, "JuanHao").ToString());
                }
                Query();
            }
        }

        private void txtpingming_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                Query();
            }
        }

        private void 打印唛头ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView2.CloseEditor();
            var fm = new 打印设置窗体();
            fm.ShowDialog();
            foreach (var s in gridView2.GetSelectedRows())
            {
                gridView2.FocusedRowHandle = s;
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Print, moban = PrintPath.唛头模板 + cmbmaitou.Text, juan =JuanHaoTableService.GetOneJuanHaoTable (x=>x.JuanHao==gridView2.GetRowCellValue (s, "JuanHao").ToString ()) }.打印();
            }
            AlterDlg.Show("所有唛头都打印完毕！");
        }

        private void 生成质检单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var juan in juanlist)
            {
                foreach (var chidian in ChiDianTableService.GetChiDianTablelst(x => x.JuanHao == juan.JuanHao))
                {
                    juan.Cidian += "{" + chidian.WeiZhi + "," + chidian.ChiDianName + "}";
                }
            }
            gridControl2.DataSource = juanlist;
            gridControl2.RefreshDataSource();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(Gridview1) { formname = this.Name, Obj =null,dt= gridControl1.DataSource as DataTable  };
            fm.ShowDialog();
        }

     

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, Gridview1);
        }

        private void 编辑报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                Tools.打印检验报告.PrintReport(PrintModel.Design, SelectHelper.CreatJuanhao(gridView2));
            }
        }
        

        private void 预览报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Privew, SelectHelper.CreatJuanhao(gridView2));
        }

        private void 打印报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Print, SelectHelper.CreatJuanhao(gridView2));
        }

        private void 导出明细ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl2, "打卷报表");
        }

        private void 导出汇总ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl1,"打卷汇总");
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintList(PrintModel.Design);
        }
        private void PrintList(PrintModel useful)
        {
            var juans = new List<JuanHaoTable>();
             
            foreach(var row in gridView2.GetSelectedRows ())
            {
                juans.Add(juanlist.FirstOrDefault(x => x.ID == (int)gridView2.GetRowCellValue(row, "ID")));
            }
            new Tools.打印清单码单()
            {
                danjuTable = new DanjuTable() ,
                danjumingxitables = new List<danjumingxitable>(),
                danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName ="gridView1" },
                juanHaoTables = juans,
                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = "gridView1" },
                JuanInfo = new Tools.FormInfo { FormName = "打卷报表", GridviewName = gridView2.Name }
            }.Print(PrintPath.报表模板 + "\\清单码单.frx", useful );
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintList(PrintModel.Privew );
        }

        private void 打卷报表_Load(object sender, EventArgs e)
        {
            cmbcheckname.DataSource = YhbService.GetYhblst().Select(x => x.YHMC).ToList();
            cmbcheckname.Text = string.Empty;
        }

        private void 分组统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (AccessBLL.CheckAccess("打卷分组统计"))
                {
                    MainForm.mainform.AddMidForm(new 打卷分组统计());
                }
                else
                {
                    Tools.ShowMessageBox.ShowErrorBox("你没有权限使用该功能！请联系管理员开通");
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("发生了错误"+ex.Message);
            }
        }

        private void Gridview1_Click(object sender, EventArgs e)
        {
            try
            {
                var stocks = SelectHelper.GetFilterOrSortDatasOfGridView(Gridview1);
                if (Gridview1.FocusedRowHandle >= 0)
                {
                    var s = stocks.Rows[Gridview1.FocusedRowHandle];
                    var juans = JuanHaoTableService.GetJuanHaoTablelst(x => x.ReceiptNo == s["RKDH"].ToString() && x.GangHao == s["GH"].ToString() && x.SampleName == s["PM"].ToString() && x.yanse == s["YS"].ToString() && x.Houzhengli == s["houzhengli"].ToString());
                    gridControl3.DataSource = juans;
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox(ex.Message);
            }
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl1, "打卷汇总");
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                var rolls = SelectHelper.CreatJuanhao(DGVDelete);
                Connect.dbcontext.BeginTran();
                Connect.dbcontext.Insertable(rolls).ExecuteCommand();
                foreach (var item in rolls)
                {
                    Connect.dbcontext.Deleteable<DeleteLog>().Where(x => x.Log.Contains(item.JuanHao)).ExecuteCommand();
                }
                Connect.dbcontext.CommitTran();
                ShowMessageBox.ShowInfoBox("恢复完成!");
                Query();
            }
            catch(Exception ex)
            {
                Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox("恢复的时候发生了错误！" + ex.Message);
            }
        }

        private void 已审核ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var rolls = SelectHelper.CreatJuanhao(gridView2);
                foreach (var item in rolls)
                {
                    item.Hetonghao = "已审核";
                }
                Connect.dbcontext.BeginTran();
                Connect.dbcontext.Updateable(rolls).ExecuteCommand();
                Connect.dbcontext.CommitTran();
                Query();
            }
            catch (Exception ex) { 
                Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox("标识审核功能的时候发生了错误！"+ex.Message );
            }
        }

        private void 反审核ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var rolls = SelectHelper.CreatJuanhao(gridView2);
                foreach (var item in rolls)
                {
                    item.Hetonghao = string.Empty;
                }
                Connect.dbcontext.BeginTran();
                Connect.dbcontext.Updateable(rolls).ExecuteCommand();
                Connect.dbcontext.CommitTran();
                Query();
            }
            catch (Exception ex)
            {
                Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox("反标识审核功能的时候发生了错误！" + ex.Message);
            }
        }
        private void gridView2_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            var rolls=gridControl2.DataSource as List<JuanHaoTable >;
            // 假设我们基于某个条件来设置颜色
            if (e.RowHandle >= 0 && e.RowHandle < gridView2.DataRowCount)
            {
                // 获取当前行的数据
                //var row = gridView2.GetDataRow(e.RowHandle);
                // 假设我们根据某个字段的值来设置颜色
                //string someFieldValue = row["Hetonghao"].ToString();

                // 设置背景色和字体色
                if (rolls[e.RowHandle].Hetonghao  == "已审核")
                {
                    //e.Appearance.BackColor = Color.CornflowerBlue; // 设置背景色
                    e.Appearance.ForeColor = Color.Red;
                }
            }
        }

        private void gridView2_Click(object sender, EventArgs e)
        {
            var roll=gridView2.GetFocusedRow() as JuanHaoTable;
            if (roll != null)
            {
                gridControl5.DataSource=Connect.dbcontext.Queryable<ChiDianTable>().Where(x => x.JuanHao ==roll.JuanHao).ToList();
            }
          
        }

        private void 修改信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rolls = SelectHelper.CreatJuanhao(gridView2);
            var fm = new 修改卷(rolls);
            fm.ShowDialog();
            gridControl2.RefreshDataSource();
        }
    }
}
